var crypto = require('crypto');
var accessControl = require('./accessControl');
var User = require('../model/user');

module.exports = function(app) {
  // http://localhost:3000/login
  app.get('/login', accessControl.checkNotLogin);
  app.get('/login', function(req, res) {
    res.render('login', {
      title: '登录',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  // http://localhost:3000/login
  app.post('/login', accessControl.checkNotLogin);
  app.post('/login', function(req, res) {
    // 生成密码的md5值
    var md5 = crypto.createHash('md5');
    var password = md5.update(req.body.password).digest('hex');

    User.get(req.body.name, function(err, user) {
      if (!user) {
        req.flash('error', '用户不存在！');
        return res.redirect('/login');
      }
      // 检查密码是否一致
      if (user.password != password) {
        req.flash('error', '密码错误！');
        return res.redirect('/login');
      }

      // 用户名密码都匹配
      req.session.user = user;
      req.flash('success', '登录成功！');
      res.redirect('/');
    });
  });

  /**
   * 登出
   */
  // http://localhost:3000/logout
  app.get('/post', accessControl.checkLogin);
  app.get('/logout', function(req, res) {
    req.session.user = null;
    req.flash('success', '登出成功！');
    res.redirect('/');
  });
}